package com.qiniuyun.threedgenerator.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.UUID;

@Component
public class FileUtils {

    private static final Set<String> ALLOWED_IMAGE_EXTENSIONS = Set.of("jpg", "jpeg", "png", "gif", "bmp");
    private static final Set<String> ALLOWED_MODEL_EXTENSIONS = Set.of("obj", "stl", "gltf", "glb", "ply");

    // 验证文件类型
    public boolean isValidImageFile(MultipartFile file) {
        String extension = getFileExtension(file.getOriginalFilename());
        return ALLOWED_IMAGE_EXTENSIONS.contains(extension.toLowerCase());
    }

    public boolean isValidModelFile(String filename) {
        String extension = getFileExtension(filename);
        return ALLOWED_MODEL_EXTENSIONS.contains(extension.toLowerCase());
    }

    // 生成唯一文件名
    public String generateUniqueFilename(String originalFilename) {
        String extension = getFileExtension(originalFilename);
        return UUID.randomUUID().toString() + "." + extension;
    }

    private String getFileExtension(String filename) {
        return FilenameUtils.getExtension(filename);
    }

    // 创建目录（如果不存在）
    public void createDirectoryIfNotExists(String path) throws IOException {
        Path directoryPath = Paths.get(path);
        if (!Files.exists(directoryPath)) {
            Files.createDirectories(directoryPath);
        }
    }
}